package com.example.sqliteviewer;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * CSV导入活动
 * 用于从CSV文件导入数据到新表
 */
public class CsvImportActivity extends AppCompatActivity implements CsvImportUtils.CsvImportListener {

    private static final int REQUEST_CODE_PICK_CSV = 101;
    private static final int STORAGE_PERMISSION_REQUEST_CODE = 102;
    
    private String databasePath;
    private EditText etTableName;
    private Button btnImport;
    private TextView tvSelectedFile;
    private TextView tvImportStatus;
    private ProgressDialog progressDialog;
    
    private Uri selectedCsvUri;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_csv_import);
        
        // 获取数据库路径
        databasePath = getIntent().getStringExtra("DATABASE_PATH");
        if (databasePath == null) {
            Toast.makeText(this, "无效的数据库路径", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        setTitle("导入CSV到新表");
        
        // 初始化视图
        etTableName = findViewById(R.id.etTableName);
        Button btnSelectFile = findViewById(R.id.btnSelectFile);
        btnImport = findViewById(R.id.btnImport);
        tvSelectedFile = findViewById(R.id.tvSelectedFile);
        tvImportStatus = findViewById(R.id.tvImportStatus);
        
        // 设置按钮点击事件
        btnSelectFile.setOnClickListener(v -> selectCsvFile());
        
        btnImport.setOnClickListener(v -> importCsvFile());
        
        // 初始状态
        updateImportButtonState();
    }
    
    /**
     * 选择CSV文件
     */
    private void selectCsvFile() {
        // 检查存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, 
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
                    STORAGE_PERMISSION_REQUEST_CODE);
            return;
        }
        
        // 打开文件选择器
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/csv");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        
        try {
            startActivityForResult(
                    Intent.createChooser(intent, "选择CSV文件"),
                    REQUEST_CODE_PICK_CSV);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 导入CSV文件
     */
    private void importCsvFile() {
        String tableName = etTableName.getText().toString().trim();
        
        if (tableName.isEmpty()) {
            Toast.makeText(this, "请输入表名", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (selectedCsvUri == null) {
            Toast.makeText(this, "请选择CSV文件", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示进度对话框
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("导入中");
        progressDialog.setMessage("正在导入数据，请稍候...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.show();
        
        // 开始导入
        CsvImportUtils.importCsvToNewTable(this, databasePath, selectedCsvUri, tableName, this);
    }
    
    /**
     * 更新导入按钮状态
     */
    private void updateImportButtonState() {
        boolean hasTableName = !etTableName.getText().toString().trim().isEmpty();
        boolean hasFile = selectedCsvUri != null;
        
        btnImport.setEnabled(hasTableName && hasFile);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_CODE_PICK_CSV && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                selectedCsvUri = data.getData();
                tvSelectedFile.setText("已选择: " + getFileName(selectedCsvUri));
                updateImportButtonState();
            }
        }
    }
    
    /**
     * 获取文件名
     */
    private String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (android.database.Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME);
                    if (nameIndex != -1) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限获取成功，选择文件
                selectCsvFile();
            } else {
                Toast.makeText(this, "需要存储权限才能选择文件", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    // CsvImportListener 接口实现
    @Override
    public void onImportProgress(int progress, int total) {
        if (progressDialog != null) {
            progressDialog.setMax(total);
            progressDialog.setProgress(progress);
        }
    }
    
    @Override
    public void onImportComplete(String tableName, int rowsImported) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        
        tvImportStatus.setText("导入成功: 已导入 " + rowsImported + " 行数据到表 '" + tableName + "'");
        tvImportStatus.setVisibility(View.VISIBLE);
        
        // 禁用导入按钮，防止重复导入
        btnImport.setEnabled(false);
        
        Toast.makeText(this, "CSV导入成功", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onImportError(String error) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        
        tvImportStatus.setText("导入失败: " + error);
        tvImportStatus.setVisibility(View.VISIBLE);
        
        Toast.makeText(this, "导入失败: " + error, Toast.LENGTH_SHORT).show();
    }
}